package com.janson.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.janson.entity.User;
import com.janson.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author Janson
 * @Date 2022/4/5 15:42
 * @Version 1.0
 */
@Controller
public class MyController{
    @Autowired
    UserMapper userMapper;
    private static boolean isLogin = false;
    @RequestMapping({"/","/index"})
    public String  toIndex(Model model){
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User)subject.getPrincipal();
        model.addAttribute("msg","hello Shrio");
        //if (isLogin){
        //    model.addAttribute("username",currentUser.getUsername());
        //}
        return "index";
    }

    @RequestMapping("/user/add")
    public String toAdd(){
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String toUpdate(Model model){
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
    //    获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //密码加密
        SimpleHash md5 = new SimpleHash("MD5", password, username);
        System.out.println(md5);
        //    封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,md5.toString());

        //执行登录,没有异常就登录成功
        try {
            subject.login(token);
            Session session = subject.getSession();
            isLogin = true;
            User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
            session.setAttribute("loginUser",user);

            return "redirect:/index";

        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "index";
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){

        return "未经授权无法访问该页面";
    }
}
